import {ai_add_record, radar_add, send_template_message} from "./utils/api.js"
import { MD5 } from "./utils/MD5.js"

//app.js
App({
  onLaunch: function() {
    const updateManager = wx.getUpdateManager()

    updateManager.onCheckForUpdate(function (res) {
      // 请求完新版本信息的回调
      // console.log(res.hasUpdate)
    })
    wx.getSystemInfo({
      success(res) {
        let new_version = '7.0.0'
        let new_system = 'iOS'+' '+'12.0'
        if (res.version <= new_version){
          wx.showModal({
            title: '提示',
            content: '您的微信版本过低,请更新至7.0.0以上版本,否则将导致某些未知问题'
          })
        }
        var test = RegExp(/iOS/)
        if (res.system.match(test) && res.system < new_system ) {
          wx.showModal({
            title: '提示',
            content: '您的ios系统版本过低,暂不适配,请更新至IOS 12.0以上版本,否则将导致某些未知问题'
          })
        }
      }
    })
    updateManager.onUpdateReady(function () {
      wx.showModal({
        title: '更新提示',
        content: '新版本已经准备好，是否重启应用？',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate()
          }
        }
      })
    })

    updateManager.onUpdateFailed(function () {
      // 新版本下载失败
    })
    this.userinfo = wx.getStorageSync('userinfo');

  },
  // onShow:function(){
  //   this.update_cart();
  // },
  getUserInfo: function(cb) {
    var that = this;
    if (this.globalData.userInfo) {
      typeof cb == "function" && cb(this.globalData.userInfo)
    } else {
      //调用登录接口
      wx.login({
        success: function() {
          wx.getUserInfo({
            success: function(res) {
              that.globalData.userInfo = res.userInfo;
              typeof cb == "function" && cb(that.globalData)
            }
          })
        }
      })
    }
  },
  wxGetSetting:function(fn){
    var that = this;
    if (that.globalData.check_scope_userInfo > 0) {
      that.globalData.authSettingUser = 1;
      typeof fn == "function" && fn(1)
    } else {
      wx.getSetting({
        success(res) {
         
          if (!res.authSetting['scope.userInfo'] && res.authSetting != undefined) {

            that.globalData.authSettingUser = 0;

            typeof fn == "function" && fn(0)
          } else {
            that.globalData.check_scope_userInfo = 1;
            that.globalData.authSettingUser = 1;
            typeof fn == "function" && fn(1)
          }


        }
      })
    }
    
  },
  requestFlag: false,
  HttpPostSend: function(url, data, cb,noCheck) {
    var that = this;
    // var baseUrl = 'https://newapi.51jlkj.com';
    var baseUrl = 'https://cs.51jlkj.com';
    // var baseUrl = 'http://192.168.0.107:8080';
    // if (noCheck != undefined && noCheck ==1){
      var tUrl = baseUrl + url;
      wx.request({
        url: tUrl,
        data: data,
        method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
        header: {
          'content-type': 'application/json'
        }, // 设置请求的 header,会对数据进行JSON序列化
        success: function (res) {
          return cb(res.data);
        },
        fail: function (res) {
          var warnMsg = {
            title: "网络超时",
            duration: 2000,
            icon: 'success'
          };
          wx.showToast(warnMsg);
          // that.error_restart()
        },
        complete: function (res) {
          //complete
        }
      });
    // }else{
    //   that.wxGetSetting(function (authSettingUser) {
    //     if (authSettingUser > 0) {
    //       // 
    //       var tUrl = baseUrl + url;
    //       wx.request({
    //         url: tUrl,
    //         data: data,
    //         method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
    //         header: {
    //           'content-type': 'application/json'
    //         }, // 设置请求的 header,会对数据进行JSON序列化
    //         success: function (res) {
    //           return cb(res.data);
    //         },
    //         fail: function (res) {
    //           var warnMsg = {
    //             title: "网络通讯超时",
    //             duration: 2000,
    //             icon: 'success'
    //           };
    //           wx.showToast(warnMsg);
    //         },
    //         complete: function (res) {
    //           //complete
    //         }
    //       });
    //     } else {
    //       return cb("-10000");
    //     }
    //   })
    // }
  },
  HttpGetSend: function (url, data, cb, noCheck) {
    // var baseUrl = 'https://newapi.51jlkj.com';
    var baseUrl = 'https://cs.51jlkj.com';
    // var baseUrl = 'https://api.51jlkj.com';
    var that = this
    
    // if (noCheck != undefined && noCheck == 1) {
      var tUrl = baseUrl + url;
      wx.request({
        url: tUrl,
        data: data,
        method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
        header: {
          'content-type': 'application/json'
        }, // 设置请求的 header,会对数据进行JSON序列化
        success: function (res) {
          return cb(res.data);
        },
        fail: function (res) {
          var warnMsg = {
            title: "网络超时",
            duration: 2000,
            icon: 'success'
          };
          wx.showToast(warnMsg);
          // that.error_restart()
        },
        complete: function (res) {
          //complete
        }
      });
    // }else{
    //   that.wxGetSetting(function (authSettingUser) {
    //     if (authSettingUser > 0) {
    //       var tUrl = baseUrl + url;
    //       wx.request({
    //         url: tUrl,
    //         data: data,
    //         method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
    //         header: {
    //           'content-type': 'application/json'
    //         }, // 设置请求的 header,会对数据进行JSON序列化
    //         success: function (res) {
    //           return cb(res.data);
    //         },
    //         fail: function (res) {
    //           var warnMsg = {
    //             title: "网络通讯超时",
    //             duration: 2000,
    //             icon: 'success'
    //           };
    //           wx.showToast(warnMsg);
    //         },
    //         complete: function (res) {
    //           //complete
    //         }
    //       });
    //     } else {
    //       return cb("-10000");
    //     }
    //   })
    // }
    
    
  },
  getSign: function (obj) {//排序的函数
    var that = this;
    var newObj = that.ksortArr(obj);
    var str = that.urlEncode(newObj);
    str = str.slice(1);
    str = str + "&key=" + 'be8bc2d6d57715920b3784df2efe2a0f';
    console.log(str);
    var md_str = MD5(str);
    return md_str.toLocaleUpperCase();
  },
  urlEncode :function (param, key, encode) {
    var that = this;
    if (param == null) return '';
    var paramStr = '';
    var t = typeof (param);
    if (t == 'string' || t == 'number' || t == 'boolean') {
      if (param === true){
        param = 1;
      } else if (param === false){
        param = 0;
      }
      paramStr += '&' + key + '=' + ((encode == null || encode) ? that.fixedEncodeURIComponent(param) : param);
    } else {
      for (var i in param) {
        var k = key == null ? i : key + (param instanceof Array ? '%5B' + i + '%5D' : '%5B' + i + '%5D');
        paramStr += that.urlEncode(param[i], k, encode);
      }
    }
    return paramStr;
  },
  fixedEncodeURIComponent:function (str) {
    return encodeURIComponent(str).replace(/[!‘()*]/g, function (c) {
      return '%' + c.charCodeAt(0).toString(16);
    })
  },
  ksortArr:  function (inputArr) {
    let sorted = {},
      keys = Object.keys(inputArr);
    keys.sort();
    keys.forEach((key) => {
      sorted[key] = inputArr[key];
    })
    return sorted;
  },
  showTipMsg: function(msg) {
    var warnMsg = {
      title: msg,
      duration: 2000,
      icon: 'success',
    };
    wx.showToast(warnMsg);
  },
  checkNullObject: function(obj) {
    if (JSON.stringify(obj) == "{}") {
      return true;
    } else {
      return false;
    }
  },
  saveSalerInfoToLocal: function(mobile, name) {
    var userinfo = {
      name: name,
      mobile: mobile
    };
    this.userinfo = userinfo;
    wx.setStorage({
      key: 'userinfo',
      data: userinfo
    });
  },
  saveMyInfoToLocal: function(token, id) {
    var loginfo = {
      token: token,
      identification: id
    };
    this.loginfo = loginfo;
    wx.setStorage({
      key: 'loginfo',
      data: loginfo
    });
  },
  getSalerInfoFromLocal: function(callback) {
    return callback(null, this.userinfo);
  },
  // cleanSalerInfo:function(){
  //      wx.clearStorage();
  //      this.userinfo = {};
  // },
  // 手机号码验证
  phoneReg: function(res) {
    var reg = /^1\d{10}$/;
    if (reg.test(res)) {
      return true;
    } else {
      return false
    }

  },
  // 添加 雷达纪录
  radarAdd: function (operation_id, type, status, goodsName,user_logo) {
    const that = this
    try {
      that.HttpGetSend(
        radar_add, {
          uid: that.globalData.userInfo.id,
          operation_id: operation_id,
          type: type,
          status: status ? status : '',
          goodsName: goodsName ? goodsName : '',
          user_logo: user_logo ? user_logo : '',
        },
        function(res) {
          // console.log(res)
          if (res.msg != "success") {
            that.showTipMsg(res.msg);
          } else {
            // console.log('成功')
          }
        })
    } catch (error) {
      console.log(error)
      console.log('网络通讯错误')
    }
  },
  // 添加 Ai 纪录
  aiAddRecord: function(type, carte_id) {
    const that = this
    let operation_id = carte_id ? carte_id : this.globalData.SwitchTabParams.v_id //当前操作卡片的 id
    try {
      that.HttpGetSend(
        ai_add_record, {
          uid: that.globalData.userInfo.id,
          operation_id: operation_id,
          type: type
        },
        function(res) {
          // console.log(res)
          if (res.msg != "success") {
            that.showTipMsg(res.msg);
          } else {
            // console.log('成功')
          }
        })
    } catch (error) {
      console.log(error)
      console.log('网络通讯错误')
    }
  },
  // 发送模板消息 
  sendTemplateMessage: function (carte_id, type, page, keyword, order_id, money, rate,mg_id) {
    const that = this
    let send_template_message_params = {
      operatorId: carte_id,
      type: type,
      uid: that.globalData.userInfo.id,
      page: page ? page : '',
      keyword: keyword ? keyword : '',
      order_id: order_id ? order_id : '',
      money: money ? money : '',
      rate: rate ? rate : '',
      mg_id: mg_id ? mg_id : ''
    }
    that.HttpGetSend(send_template_message, send_template_message_params, function(res) {
      // console.log(res)
      if (res.msg != "success") {
        
      } else {

      }
    })
  },

  update_cart: function (uid){
    var that = this;
    var url2 = '/cart/goods_num';
    var params2 = {
      uid: uid,
      mg_uid: 0
    };
    that.HttpGetSend(url2, params2, function (res) {
      // console.log(res.data);
      if (res.data>0){
        wx.setTabBarBadge({
          index: 2,
          text: String(res.data)
        })
      }
      
    });
  },
  onError: function (msg) {
    
  },
  error_restart:function(){
    wx.showModal({
      title: '警告',
      content: '网络不佳',
      showCancel: true,
      success: function () {
        var that = this;
        var pages = getCurrentPages()
        var currentPage = ''
        console.log(pages.length)
        if (pages.length == 1) {
          currentPage = pages[pages.length - 1]

        } else {
          currentPage = pages[pages.length - 2]
        }
        console.log(currentPage)
        var url = currentPage.route
        var options = currentPage.options
        let urlWithArgs = `/${url}?`
        for (let key in options) {
          const value = options[key]
          urlWithArgs += `${key}=${value}&`
        }
        urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1)
        var persontest = /\/person\/person/;
        var carteShowtest = /\/carteShow\/carteShow/;
        var shoptest = /\/shop\/shop/;
        var buyCartest = /\/buyCar\/buyCar/;

        if (!persontest.test(urlWithArgs) && !carteShowtest.test(urlWithArgs) && !shoptest.test(urlWithArgs) && !buyCartest.test(urlWithArgs)) {
          wx.redirectTo({
            url: urlWithArgs,
          })
        } else {
          wx.switchTab({
            url: urlWithArgs,
          })
        }

      }
    })
  },
  globalData: {
    userInfo: null,
    SwitchTabParams: {},
    shareOptions: {},
    currentCity:'',
    currentCode: 0,
    latitude:0,
    longitude:0,
    authSettingUser:0,
    check_scope_userInfo:0,
    appIdKey:'wx13693f2be43ce129',

    // bossradar: 'https://csboss.51jlkj.com',
    bossradar: 'https://csboss1.51jlkj.com',//测试boosAPI
    // bossradar: 'http://192.168.1.107:8080',
  
    ENUM_LOG : {

      //个人
      P_UP: 1,//点赞
      P_COLLECT: 2,//收藏
      P_SAVEPOSTER: 30,//保存海报
      P_SHARE: 3,//分享
      P_VIST: 5,//浏览

      M_VIST: 13,// 浏览
      M_ADDCART: 31,//加购物车
      M_BUY: 18,//下单
      M_SHARE: 32,//分享
      M_SAVEPIC: 33,//保存图片

      CHART: 6,//聊天
      VISTWEB: 7,//访问官网
      VIDEO: 9,//视频
      VOICE: 10,//语音
      CLICKBUYCARD: 14,//点击购买名片
      BUYCARD: 34,//购买名片
      BUYCARDSUCCESS: 35,//购买名片成功
      DELIVERY: 17,//点击收货地址
      PRODUCTNUM: 18,//提交商品订单数
      PAYSUCCESS: 19,//付款成功
      CANCLEORDER: 20,//取消订单
      DYNAMICP: 21,//动态点赞
    }
  },
  userinfo: {},
  loginfo: {},


  //添加雷达足迹
  addlog: function (operationId, operationName, uid, userName, userImg, logType, goodName) {
    console.log("==============================");
    var that = this;
    var share_uid = that.globalData.share_uid;
    var is_share = 0;
    if (share_uid > 0) {
      is_share = 1;
    }
    wx.request({
      url: that.globalData.bossradar + '/api/1.0/saveLog',
      data: {
        operationId: operationId,
        operationName: operationName,
        uid: uid,
        userName: userName,
        logType: logType,
        goodName: goodName,
        shareId: share_uid,
        isShare: is_share
      },
      method: 'POST',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        console.log(res.data)
      }
    })

  },

  addlog_v2: function (operationId, operationName, uid, userName, userImg, logType, goodName, share_uid,is_share) {
    console.log("==============================");
    var that = this;
    wx.request({
      url: that.globalData.bossradar + '/api/1.0/saveLog',
      data: {
        operationId: operationId,
        operationName: operationName,
        uid: uid,
        userName: userName,
        logType: logType,
        goodName: goodName,
        shareId: share_uid,
        isShare:is_share
      },
      method: 'POST',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        console.log(res.data)
      }
    })
  }

})